package com.xiaoyang.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Random;

/**
 * @auther XiaoYang
 * @DATE 2022/12/15-19:50
 */
@Component
public class SendEmail {
    // 用于发送邮件的对象
    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 生成随机验证码
     * @param number 几位数
     * @return 验证码(字符串)
     */
    public String generateVerifyCode(int number) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i <= number; i++) {
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }

    /**
     * 发送验证码
     * @param code 验证码
     * @param from 从哪来
     * @param to 发到哪
     */
    public boolean sendEmailCode(String code, String from, String to) {
        try {
            // 用来设置邮件信息
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            // 设置邮件标题
            simpleMailMessage.setSubject("登录验证码");
            // 设置邮件内容
            simpleMailMessage.setText("尊敬的用户:你好! 注册验证码为:" + code + "(有效期为一分钟)");
            // 设置源邮箱
            simpleMailMessage.setFrom(from);
            // 设置目的邮箱
            simpleMailMessage.setTo(to);

            //simpleMailMessage.setSentDate(new Date());

            // 发送
            javaMailSender.send(simpleMailMessage);
            // 没有出现异常，正常发送，返回true
            return true;
        } catch (MailException e) {
            // 发送过程中，发生错误，打印错误信息，返回false
            e.printStackTrace();
            return false;
        }
    }

}
